package xupt.com.bolg.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import xupt.com.bolg.entity.Bolg;
import xupt.com.bolg.entity.Comn;
import xupt.com.bolg.entity.User;
import xupt.com.bolg.service.impl.BolgServiceImpl;
import xupt.com.bolg.service.impl.ComnServiceImpl;
import xupt.com.bolg.service.impl.UserServiceImpl;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Controller
public class ComnController {
    @Autowired
    ComnServiceImpl comnService;
    @Autowired
    UserServiceImpl userService;
    @Autowired
    BolgServiceImpl bolgService;
    @PostMapping("/sendcolmn")
    public String sendColumn(Comn comn, HttpServletRequest request, Model model){
        //这儿没写好；；；；；；；；
       Integer   bolgid =(Integer)request.getSession().getAttribute("bolgid");
        comn.setData(new Date());
        String  name =(String) request.getSession().getAttribute("name");
        User byName = userService.findByName(name);
        comn.setUserid(byName.getId());
        comn.setBolgid(bolgid);
        comn.setUsername(byName.getName());
        comnService.save(comn);
        List<Comn> comns = comnService.findcomnByBolgID(bolgid);
        Bolg byID = bolgService.findByID(bolgid);
        model.addAttribute("bolg",byID);
        model.addAttribute("comns",comns);
        return "bolg/bolginformation";
    }

    /*显示的时候要判断权限，是否可以给删除按钮：
    *可以删除自己博客的所有评论，
    * 可以删除自己的评论；
    * 删除成功后返回到，具体的bolg页面
    * */

    @GetMapping("/comn/delete")
    public String deleteComn(HttpServletRequest request,Model model){
        //动态拼串在 request域取值
        String s= request.getParameter("id");
        Integer id = Integer.valueOf(s);
        Comn byID = comnService.findByID(id);
        String  name =(String) request.getSession().getAttribute("name");
        User byName = userService.findByName(name);
        Bolg byID2 = bolgService.findByID(byID.getBolgid());
        boolean b=false;
        //自己的评论可以删除
        if(byID.getUserid()==byName.getId()){
            //删除成功
            b = comnService.deleteByID(byID.getId());
        }
        //自己的博客可以删除评论
        if(byID2.getUserid()==byName.getId()){
            b=comnService.deleteByID(byID.getId());
        }
        if(b){
            request.setAttribute("msg","删除成功");
        }else {
            request.setAttribute("msg","删除失败");
        }
        Bolg byID1 = bolgService.findByID(byID.getBolgid());
        List<Comn> comns = comnService.findcomnByBolgID(byID.getBolgid());
        model.addAttribute("bolg",byID1);
        model.addAttribute("comns",comns);
        return "bolg/bolginformation";
    }
}
